﻿using System.Collections.Generic;
using System.Web.Mvc;
using Web7.Ioc;

namespace Web7.Mvc.ActionInvokers
{
    public interface IFilterProvider : IDependency
    {
        void AddFilters(FilterInfo filterInfo);
    }

    public abstract class FilterProvider : IFilterProvider
    {
        void IFilterProvider.AddFilters(FilterInfo filterInfo)
        {
            AddFilters(filterInfo);
        }

        protected virtual void AddFilters(FilterInfo filterInfo)
        {
            if (this is IAuthorizationFilter)
                filterInfo.AuthorizationFilters.Add(this as IAuthorizationFilter);
            if (this is IActionFilter)
                filterInfo.ActionFilters.Add(this as IActionFilter);
            if (this is IResultFilter)
                filterInfo.ResultFilters.Add(this as IResultFilter);
            if (this is IExceptionFilter)
                filterInfo.ExceptionFilters.Add(this as IExceptionFilter);
        }

    }

    public class FilterControllerActionInvoker : ControllerActionInvoker
    {
        private readonly IEnumerable<IFilterProvider> _filterProviders;

        public FilterControllerActionInvoker(IEnumerable<IFilterProvider> filterProviders)
        {
            _filterProviders = filterProviders;
        }

        protected override FilterInfo GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
        {
            var filters = base.GetFilters(controllerContext, actionDescriptor);
            foreach (var provider in _filterProviders)
            {
                provider.AddFilters(filters);
            }
            return filters;
        }
    }
}
